layui.config({
    base: '/cropper/layui_modules/' //你存放新模块的目录，注意，不是layui的模块目录
}).use('cropperUpload'); //加载入口

layui.use(['element','form','table','layer','laydate','layedit','cropperUpload'],function () {
    var element = layui.element;
    var form=layui.form;
    var table=layui.table;
    var layer=layui.layer;
    var laydate=layui.laydate;
    var layedit=layui.layedit;
    var cropperUpload = layui.cropperUpload;


    form.verify({
        http: [
            /^(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]$/
            ,'不是正确的网页地址，请重新输入'
        ]
    });

    //日期时间选择器
    laydate.render({
        elem: '#startTime'
        ,type: 'datetime'
    });
    //日期时间选择器
    laydate.render({
        elem: '#endTime'
        ,type: 'datetime'
    });



    var tableIns = table.render({
        elem: '#garouselTable',
        url: '/admin/garousel/garouselList',
        toolbar: '#garouselToolBar',
        page: 'true',
        title: '轮播图表',
        cols: [ [
            {type:'checkbox'},
            {field:'id',title:'ID',align:'center'},
            {field:'title',title:'标题',align:'center'},
            {field:'imageURL',title: '图片', width:120, templet: function(d) {
                    return '<div onclick="show_img(this)" ><img src="'+d.imageUrl+'" alt="" width="50px" height="50px"></a></div>';
                }},
            {field:'sort',title:'排序',sort: true,align:'center'},
            {field:'createTime',title:'创建时间',align:'center'},
            {field:'changeTime',title:'修改时间',align:'center'},

            {title:'操作',toolbar:'#garouselRowBar',width:250}
        ] ],
        done:function (res,curr,count) {
            if(curr>1 && res.data.length==0){
                tableIns.reload({
                    page:{curr:curr-1}
                });

            }
        }
    });



    //表单封面裁剪图片组件
    formCoverUpload = cropperUpload.init({
        select : "#formCoverUpload",
        aspectRatio : 16 / 9,
        imgWidth : 750,
        imgHeight : 300,
        formDataId : "#dataFrm",
        success : function(base64Img,blog,that) { //base64Img  base64格式图片    blog  二进制图
            $("#showImg").attr("src", base64Img)
        }
    })


    //判断排序是否重复
    var isSort = false;
    $('input[name=sort]').blur(function() {
        var sort = $(this).val();
        var id = $('input[name=id]').val();
        $.get("/admin/garousel/isSortCount",{"id":id,"sort":sort},function (res) {
            layer.msg(res.content);
            if(res.success){
                isSort = true;
            }
        },"json");

    });



    form.on("submit(doSearch)",function (data) {
        tableIns.reload({
            url:'/admin/garousel/garouselList',
            where:data.field,
            page:{
                curr:1
            }
        })
        return false;
    })

    table.on('toolbar(garouselTable)',function (obj) {
        switch (obj.event) {
            case "add":
                openAddGarouselLayer();
                break;
            case "batchDelete":
                batchDelete();
                break;
        }
    })
    table.on('tool(garouselTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case "update":
                openUpdateGarouselLayer(data);
                break;
            case "delete":
                deleteInfo(data);
                break;
            case "show":
                showGarousel(data);
                break;
        }
    })

    //弹出层索引
    var mainIndex;
    //提交路径
    var url;

    //查看轮播图
    function  showGarousel(data) {
        mainIndex = layer.open({
            type:1,
            content:$("#showGarouselDiv"),
            area:["800px","500px"],
            title:"查看轮播图",
            success:function () {
                $("#show_id").html(data.id);
                $("#show_title").html(data.title);
                $("#show_http").html(data.httpUrl);
                $("#show_img").attr("src",data.imageUrl);
            }
        });
    }

    //添加
    function openAddGarouselLayer() {
        mainIndex = layer.open({
            type:1,
            content:$("#addOrUpdateDiv"),
            area:["600px","500px"],
            title:"发布轮播图",
            success:function () {

                $("#dataFrm")[0].reset();
                url="/admin/garousel/addGarousel";
                $("#showImg").attr("src","");
            }
        });

    }
    //修改
    function openUpdateGarouselLayer(data) {
        console.log(data.imageUrl);
        console.log(data.id);
        mainIndex = layer.open({
            type:1,
            content:$("#addOrUpdateDiv"),
            area:["600px","500px"],
            title:"更新轮播图",
            success:function () {
                //装载新的数据
                form.val("dataFrm",data);
                $("#showImg").attr("src",data.imageUrl+"");
                url="/admin/garousel/updateGarousel";
            }
        });
    }
    //删除
    function deleteInfo(data){
        layer.confirm("确定要删除这条数据吗？",{icon:3,title:"提示"},function (index) {
            $.post("/admin/garousel/deleteById",{"id":data.id,"imageUrl":data.imageUrl},function (result) {
                if(result.success){
                    tableIns.reload();
                }
                layer.msg(result.content);
            },"json")
            //关闭弹窗
            layer.close(index);
        })
    }

    //批量删除
    function batchDelete(){
        //获取选中的行
        var checkStatus = table.checkStatus("garouselTable");
        //判断是否选中行
        var length = checkStatus.data.length;
        if(length>0){
            layer.confirm('确定要删除这些数据吗?',{icon:3,title:"提示"},function (index) {
                var data = checkStatus.data;
                var idArr = []
                var imageArr = []
                for(var i = 0 ; i<length;i++){
                    idArr.push(data[i].id);
                    imageArr.push(data[i].imageUrl)
                }
                var ids = idArr.join(",");
                var images = imageArr.join(",");
                $.post("/admin/garousel/batchDelete",{"ids":ids,"images":images},function (result) {
                    if(result.success){
                        tableIns.reload();
                    }
                    layer.msg(result.content);
                },"json")
            })
            layer.close(index);
        }else{
            layer.alert("请选择要删除的行",{icon:0})
        }
    }

    //提交事件
    form.on("submit(doSubmit)",function (data) {
        console.log($("#dataFrm").serialize())
        if(isSort){
            formCoverUpload.ajaxPost(url, function(res) {
                if(res.success){
                    //提示信息
                    layer.msg(res.content,{icon:1});
                    //刷新数据表格
                    tableIns.reload();
                    //关闭窗口
                    layer.close(mainIndex);
                }else {
                    layer.msg(res.content,{icon:2});
                }
            },$("#dataFrm").serialize())
        }else{
            layer.msg("排序不能重复")
        }


        return false;
    })


});